package spring.boot.jwt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import spring.boot.jwt.common.Results;
import spring.boot.jwt.model.TUser;
import spring.boot.jwt.service.TUserService;
import spring.boot.jwt.vo.TUserVO;

@RestController
public class LoginController {

    @Autowired
    private TUserService userService;

    @PostMapping("/login")
    public Results login(@RequestBody TUserVO tUserVO) {
        if (tUserVO == null || tUserVO.getUsername() == null || tUserVO.getPassword() == null) {
            return Results.paramError("用户名或者密码不能为空");
        }
        TUser user = userService.selectByUsername(tUserVO.getUsername());
        if (user == null) {
            return Results.loginError();
        } else {
            if (!new BCryptPasswordEncoder().matches(tUserVO.getPassword(), user.getPassword())) {
                return Results.loginError();
            } else {
                String token = userService.getToken(user);
                return Results.success(token);
            }
        }
    }

    @GetMapping("/error")
    public Results error() {
        return Results.error();
    }

}
